package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// historyServlet:在  goods2.html页面中点击历史记录按钮，
// 执行该servlet，在该servlet中取出浏览器客户端的历史记录的cookie并将商品历史记录响应给浏览器。
@WebServlet("/historyServlet")
public class HistoryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理响应乱码
        response.setContentType("text/html;charset=utf-8");
        //获取历史记录（Cookie）
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("history".equals(name)) {
                    //将该历史记录的商品信息切割展示到页面上
                    String value = cookie.getValue();
                    String[] s = value.split("_");
                    for (String s1 : s) {
                        if ("galaxy".equals(s1)) {
                            //响应给前端数据
                            response.getWriter().println("三星手机");
                        } else if ("chuizi".equals(s1)) {
                            response.getWriter().println("锤子手机");
                        } else if ("xiaomi".equals(s1)) {
                            response.getWriter().println("小米手机");
                        }
                    }
                }
            }
        }else {
            //如果没有浏览过任何商品
            response.getWriter().println("你暂未浏览过任何商品！！！");
        }
        //给个超链接
        response.getWriter().print("<br><a href=\"/goods.html\">继续浏览</a>");
    }
}